package com.lzx.iteam;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.R;
import com.lzx.iteam.contactssearch.ContactsDBReader;
import com.lzx.iteam.net.*;
import com.lzx.iteam.task.UpLoadContactsTask;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PhotoUtil;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

import static android.R.id.candidatesArea;
import static android.R.id.message;
import static com.lzx.iteam.DialerApp.mContext;

/**
 * Created by zhangshuai on 15-3-18.
 */
public class MySettingActivity extends Activity implements View.OnClickListener {

    private LocalLogin login;
    private TextView mComplete, mTvManagerIn;
    private ImageView mPhoto;
    private EditText mName;
    private EditText mCompany;
    private EditText mOrganization;
    private PopupWindow mSetPhotoPop;
    private LinearLayout mMainView;
    private File mCurrentPhotoFile;
    private Bitmap imageBitmap;
    private Uri imageUri;
    private Uri mAvatarUri;
    private final String IMAGE_FILE = Environment.getExternalStorageDirectory() + "/Yun/Images";
    private final String IMAGE_FILE_LOCATION = Environment.getExternalStorageDirectory() + "/Yun/Images/avatar_crop";
    private final String IMAGE_FILE_PHOTO = Environment.getExternalStorageDirectory() + "/Yun/Images/avatar_test";
    private MySettingActivity mActivity;
    private PreferenceUtil mPreferenceUtil;
    private String mContactName;
    private String mContactCompany;
    private String mContactOrganization;
    private String mRongToken;

    private int type;//0:管理员进入  1：员工进入

    private final int SETTING_NAME = 102;
    private final int PHOTO_PICKED_WITH_DATA = 3881;
    private final int CAMERA_WITH_DATA = 3884;
    private final int GET_QN_TOKEN = 3885;
    private final int CROP_PHOTO = 3886;

    private final int MSG_GET_NAMECARD = 1789;
    private final int MSG_RONG_TOKEN = 2010;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SETTING_NAME:
                    if (msg.arg1 == 0) {
                        mPreferenceUtil.save("my_user_name",mContactName);
                        getRongToken();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mActivity, R.string.active_failure_no_network,
                                  Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mActivity, (String) msg.obj,
                                  Toast.LENGTH_LONG).show();
                        }
                    }

                    break;
                case GET_QN_TOKEN:
                    if (msg.arg1 == 0) {
                        Map<String, Object> map = (HashMap<String, Object>) msg.obj;
                        String token = (String) map.get("token");
                        byte[] file = (byte[]) map.get("file");
                        String fileName = (String) map.get("fileName");
                        setPhoto(token, file, fileName);
                    }

                    break;
                case MSG_GET_NAMECARD:
                    if (msg.arg1 == 0) {

                    } else {
                        Toast.makeText(MySettingActivity.this, (String) msg.obj,
                              Toast.LENGTH_LONG).show();
                    }
                    break;
                case MSG_RONG_TOKEN:
                    if (msg.arg1 == 0) {
                        try {
                            JSONObject item = ((JSONObject) msg.obj).getJSONObject(AsynHttpClient.KEY_CC_DATA);
                            mRongToken = item.getString("token");
                            connectRongYun();

                        } catch (JSONException e) {
                            Log.e("JSONException", e.toString());
                        }
                    } else {
                        Toast.makeText(mContext, (String) msg.obj,
                              Toast.LENGTH_LONG).show();
                    }
                    break;
            }

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_setting_layout);
        initView();
        initProperty();
        //new UpLoadContactsTask(this).execute();
    }

    public void initView() {
        mMainView = (LinearLayout) findViewById(R.id.my_setting_ll);
        mComplete = (TextView) findViewById(R.id.register_ok);
        mTvManagerIn = (TextView) findViewById(R.id.tv_manager_in);
        mComplete.setOnClickListener(this);
        mTvManagerIn.setOnClickListener(this);
        mPhoto = (ImageView) findViewById(R.id.register_my_photo);
        mPhoto.setOnClickListener(this);
        mName = (EditText) findViewById(R.id.register_my_name);
        mCompany = (EditText) findViewById(R.id.register_my_company);
        mOrganization = (EditText) findViewById(R.id.register_my_organization);
    }

    public void initProperty() {
        mActivity = this;
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        login = LocalLogin.getInstance();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register_my_photo:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showSetPhotoPop();
                break;
            case R.id.register_ok:

                mContactName = mName.getText().toString().trim();
                mContactCompany = mCompany.getText().toString().trim();
                mContactOrganization = mOrganization.getText().toString().trim();
                // TODO 如果名字不是空的就创建新的联系人，否则不创建

                if (StringUtil.isEmpty(mContactName)) {
                    Toast.makeText(mActivity, "名字不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (StringUtil.isEmpty(mContactCompany)) {
                    Toast.makeText(mActivity, "公司不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (StringUtil.isEmpty(mContactOrganization)) {
                    Toast.makeText(mActivity, "职位不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                type=1;
                nameMessage();
                break;
            case R.id.tv_manager_in:
                mContactName = mName.getText().toString().trim();
                mContactCompany = mCompany.getText().toString().trim();
                mContactOrganization = mOrganization.getText().toString().trim();
                // TODO 如果名字不是空的就创建新的联系人，否则不创建

                if (StringUtil.isEmpty(mContactName)) {
                    Toast.makeText(mActivity, "名字不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (StringUtil.isEmpty(mContactCompany)) {
                    Toast.makeText(mActivity, "公司不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (StringUtil.isEmpty(mContactOrganization)) {
                    Toast.makeText(mActivity, "职位不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                type=0;
                nameMessage();
                break;
        }
    }

    /**
     * 弹出拍照和从相册选择popwindow
     */
    private void showSetPhotoPop() {
        View mainView = LayoutInflater.from(this).inflate(R.layout.alert_setphoto_menu_layout, null);
        Button btnTakePhoto = (Button) mainView.findViewById(R.id.btn_take_photo);
        btnTakePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSetPhotoPop.dismiss();
                doTakePhoto();
            }
        });
        Button btnCheckFromGallery = (Button) mainView.findViewById(R.id.btn_check_from_gallery);
        btnCheckFromGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSetPhotoPop.dismiss();
                doPickPhotoFromGallery();
            }
        });
        Button btnCancle = (Button) mainView.findViewById(R.id.btn_cancel);
        btnCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSetPhotoPop.dismiss();
            }
        });
        mSetPhotoPop = new PopupWindow(this);
        mSetPhotoPop.setBackgroundDrawable(new BitmapDrawable());
        mSetPhotoPop.setFocusable(true);
        mSetPhotoPop.setTouchable(true);
        mSetPhotoPop.setOutsideTouchable(true);
        mSetPhotoPop.setContentView(mainView);
        mSetPhotoPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mSetPhotoPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mSetPhotoPop.setAnimationStyle(R.style.bottomStyle);
        mSetPhotoPop.showAtLocation(mMainView, Gravity.BOTTOM, 0, 0);
        mSetPhotoPop.update();
    }

    /**
     * 调用系统相机拍照
     */
    protected void doTakePhoto() {
        try {

            File yunDir = new File(IMAGE_FILE);
            if (!yunDir.exists()) {
                yunDir.mkdirs();
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
            mAvatarUri = Uri.fromFile(new File(IMAGE_FILE_PHOTO));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mAvatarUri);

            startActivityForResult(intent, CAMERA_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Constructs an intent for capturing a photo and storing it in a temporary
     * file.
     */
    public static Intent getTakePickIntent(File f) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        return intent;
    }

    /**
     * 剪切图片
     */
    protected void doCropPhoto(File f) {
        try {
            // Add the image to the media store
            MediaScannerConnection.scanFile(this, new String[]{
                  f.getAbsolutePath()
            }, new String[]{
                  null
            }, null);

            // Launch gallery to crop the photo
            final Intent intent = getCropImageIntent(Uri.fromFile(f));
            startActivityForResult(intent, CROP_PHOTO);
        } catch (Exception e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
        }
    }

    private static final int ICON_SIZE = 96;

    /**
     * 获取系统剪裁图片的Intent.
     */
    public static Intent getCropImageIntent(Uri photoUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(photoUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", ICON_SIZE);
        intent.putExtra("outputY", ICON_SIZE);
        intent.putExtra("return-data", true);
        return intent;
    }

    /**
     * 从相册选择图片
     */
    protected void doPickPhotoFromGallery() {
        try {
            // Launch picker to choose photo for selected contact
            final Intent intent = getPhotoPickIntent();
            startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 获取调用相册的Intent
     */
    public static Intent getPhotoPickIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        return intent;
    }

    /**
     * 向服务器发送数据
     *
     * @param
     */
    public void nameMessage() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_NAME, mContactName));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_COMPANY, mContactCompany));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_JOB, mContactOrganization));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_EMAIL, ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ADDRESS, ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SEX, ""));
        NameMessage message;
        message = new NameMessage(mHandler.obtainMessage(SETTING_NAME));
        message.mApi = AsynHttpClient.API_USER_GOON;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execUserHttp(message);
    }


    public static class NameMessage extends CcMsgStructure {

        private Message mmCallback;

        public NameMessage(Message callback) {
            this.mmCallback = callback;
        }

        @Override
        public void onReceive(JSONObject data) {

            if (mmCallback != null) {
                mmCallback.arg1 = 0;
                mmCallback.sendToTarget();
            }

        }

        @Override
        public void onError(int error, Object ret) {

            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }


    public void getQnToken(byte[] file) {
        String fileName = UUID.randomUUID().toString() + System.currentTimeMillis();
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        String sid = LocalLogin.getInstance().mSid;
        if (sid.equals(LocalLogin.VISITOR_SID)) {
            LocalLogin.getInstance().login(this);
            sid = LocalLogin.getInstance().mSid;
        }
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, sid));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_KEY, fileName));
        GetQnTokenMsg getQnTokenMsg = new GetQnTokenMsg(mHandler.obtainMessage(GET_QN_TOKEN), file, fileName);
        getQnTokenMsg.mApi = AsynHttpClient.API_QN_GET_US_TOKEN;
        getQnTokenMsg.mParams = mList;
        AsynHttpClient.getInstance(this).execUserHttp(getQnTokenMsg);
    }

    public void setPhoto(String token, byte[] file, String fileName) {
        Log.d("七牛--token", token);
        Log.d("七牛--fileName", fileName);
        DialerApp.getUploadManager(this).put(file, fileName, token,
              new UpCompletionHandler() {
                  @Override
                  public void complete(String key, ResponseInfo info, JSONObject response) {
                      Log.d("七牛--info.isOk()", info.isOK() + "--response" + response);
                      mPhoto.setImageBitmap(imageBitmap);
                      Toast.makeText(mActivity, "设置头像成功", Toast.LENGTH_SHORT).show();
                  }
              }, null);
    }

    /**
     * 093.
     * 收缩图片
     *
     * @param uri
     */
    private final int PHOTO_CROP_RESOULT = 1111;

    public void startPhotoZoom(Uri uri) {
        File yunDir = new File(IMAGE_FILE);
        if (!yunDir.exists()) {
            yunDir.mkdirs();
        }
        imageUri = Uri.fromFile(new File(IMAGE_FILE_LOCATION));

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("circleCrop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", ICON_SIZE);
        intent.putExtra("outputY", ICON_SIZE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//图像输出
        intent.putExtra("outputFormat",
              Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", false);//回调方法data.getExtras().getParcelable("data")返回数据为空
        startActivityForResult(intent, PHOTO_CROP_RESOULT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            switch (requestCode) {
                case PHOTO_PICKED_WITH_DATA:
                    startPhotoZoom(data.getData());
                    break;
                case CAMERA_WITH_DATA:
                    Bitmap photoBitmap = PhotoUtil.readBitmapFromPath(this, IMAGE_FILE_PHOTO, false);
                    int degree = PhotoUtil.getExifOrientation(IMAGE_FILE_PHOTO);
                    if (degree != 0) {
                        photoBitmap = PhotoUtil.rotaingImageView(photoBitmap, degree);
                        if (mCurrentPhotoFile == null) {
                            mCurrentPhotoFile = new File(IMAGE_FILE_LOCATION);
                        }
                        mCurrentPhotoFile = PhotoUtil.saveBitmaptoSdCard("avatar_test", photoBitmap, this, "/Yun/Images");
                        startPhotoZoom(Uri.fromFile(mCurrentPhotoFile));
                    } else {
                        startPhotoZoom(mAvatarUri);
                    }

                    break;
                case PHOTO_CROP_RESOULT:
                    imageBitmap = getBitmapFromUri(imageUri);
                    if (imageBitmap != null) {
                        getQnToken(PhotoUtil.compressAvatarImage(imageBitmap));
                    } else {
                        Toast.makeText(MySettingActivity.this, "设置头像失败", Toast.LENGTH_SHORT).show();
                    }
                    break;

            }
        }
    }

    private Bitmap getBitmapFromUri(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (Exception e) {
            Log.e("PhotoError ", "mysetting error  = " + e.toString());
            return null;
        }
        return bitmap;
    }

    /**
     * 获取名片信息
     */
    private void uploadNameCard() {

        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));

        NameCardMessage message = new NameCardMessage(mHandler.obtainMessage(MSG_GET_NAMECARD), this);
        message.mApi = AsynHttpClient.API_USER_MYNAMECARD;
        message.mParams = mList;
        AsynHttpClient.getInstance(this).execUserHttp(message);

    }

    private void getRongToken() {

        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID_OLD, LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ID, mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "")));

        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_RONG_TOKEN));
        msg.mApi = AsynHttpClient.API_RONG_CHAT_TOKEN;
        msg.mParams = nvps;
        msg.type = 1;
        AsynHttpClient.getInstance(this).execRongHttp(msg);


    }

    private void connectRongYun() {
        /**
         * IMKit SDK调用第二步,建立与服务器的连接
         */
        RongIM.connect(mRongToken, new RongIMClient.ConnectCallback() {

            /**
             * Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的 Token
             */
            @Override
            public void onTokenIncorrect() {
                getRongToken();
                Log.d("融云connect", "--onTokenIncorrect");
            }

            /**
             * 连接融云成功
             * @param userid 当前 token
             */
            @Override
            public void onSuccess(String userid) {

                Log.d("融云connect", "--onSuccess" + userid);
                mPreferenceUtil.save(AsynHttpClient.KEY_RONG_TOKEN, mRongToken);
                Log.d("融云connect_token", mPreferenceUtil.getString(AsynHttpClient.KEY_RONG_TOKEN, "dddd"));
                if(type==1){
                    Intent intent = new Intent(mActivity, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                    mActivity.finish();
                }else{
                    Intent intent = new Intent(mActivity, CreateGroupActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    intent.putExtra("type",1);
                    startActivity(intent);
                    mActivity.finish();
                }

                Toast.makeText(mActivity, "设置成功", Toast.LENGTH_SHORT).show();
            }

            /**
             * 连接融云失败
             * @param errorCode 错误码，可到官网 查看错误码对应的注释
             */
            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

                Log.d("融云connect", "--onError" + errorCode);
            }
        });
    }


}
